package com.test.security.example02;

import java.security.Principal;
import java.security.PrivilegedAction;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

/**
 * .
 * https://blog.csdn.net/qq_21383435/article/details/85340240
 *
 * @author: bcc
 * 2020/6/9
 */
public class App {
    public static void main(String[] args) {
        System.setProperty("java.security.auth.login.config", "D:\\gitee\\javatest\\src\\main\\resources\\security.example02.config");
        System.setProperty("java.security.policy", "D:\\gitee\\javatest\\src\\main\\resources\\security.example02.policy");

        System.setSecurityManager(new SecurityManager());
        LoginContext context = null;
        try {
            //创建登录上下文
            context = new LoginContext("Demo", new DemoCallbackHander());
            //进行登录，登录不成功则系统退出
            context.login();
        } catch (LoginException le) {
            System.err.println("Cannot create LoginContext. " + le.getMessage());
            System.exit(-1);
        } catch (SecurityException se) {
            System.err.println("Cannot create LoginContext. " + se.getMessage());
            System.exit(-1);
        }

        //访问资源
        Subject subject = context.getSubject();

        System.out.println(subject);

        for (Principal principal : subject.getPrincipals()) {
            System.out.println("\t" + principal.toString());
        }

        //该方法调用需要"doAsPrivileged"权限
        Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                System.out.println(System.getProperty("java.home"));
                return null;
            }
        }, null);
    }
}
